package com.superjson.showpro.controller;

import com.alibaba.fastjson.JSONObject;
import com.beantools.annotation.handler.NotNullHandler;
import com.beantools.util.StringUtil;
import com.superjson.showpro.controller.core.BaseContoller;
import com.superjson.showpro.entity.User;
import com.superjson.showpro.service.UserService;
import com.superjson.showpro.shared.enums.SignInTypeEnum;
import com.superjson.showpro.shared.result.Result;
import com.superjson.showpro.shared.result.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.beantools.util.ObjectUtil.isNotNull;
import static com.beantools.util.ObjectUtil.isNull;
import static com.beantools.util.StringUtil.isAnyBlank;
import static com.superjson.showpro.constants.SessionConstant.*;
import static com.superjson.showpro.shared.enums.SignInTypeEnum.SIGN_IN_TYPE_ENTERPRISE;
import static com.superjson.showpro.shared.result.ResultCodeEnum.ERR_USERNAME_OR_PHONE;
import static com.superjson.showpro.shared.result.ResultCodeEnum.NOT_EMPTY_USERNAME_PHONE;
import static com.superjson.showpro.shared.util.CommonUtil.ifNullThrow;
import static com.superjson.showpro.shared.util.CommonUtil.ifTrueThrow;

/**
 * Created By zby on 20:00 2019/5/22
 *
 * @author zby
 * @version 1.1.0
 */
@RestController("userController")
@RequestMapping("/user")
public class UserController extends BaseContoller {

    @Autowired
    private UserService userService;


    /**
     * Created By zby on 11:27 2019/6/5
     * 注册
     */
    @RequestMapping(value = "/signIn", method = RequestMethod.POST)
    public Result saveUser(User user, HttpServletRequest request) {
        try {
            NotNullHandler.getInstance().validate(user);
            userService.saveUser(user, request);
            return ResultUtil.buildSuccess();
        } catch (Exception e) {
            return ResultUtil.buildFailed(e.getMessage());
        }
    }

    /**
     * Created By zby on 11:28 2019/6/5
     * 根据账户名、手机号查询用户是否存在
     *
     * @param phoneOrAccName 目前是手机号码、账户名称
     * @param companyName    公司名称
     */
    @RequestMapping(value = "/existUser", method = RequestMethod.GET)
    public Result existUser(String phoneOrAccName, String companyName) {
        User user = userService.existUser(phoneOrAccName, companyName).getResultData();
        return ResultUtil.buildSuccess(isNotNull(user) ? "EXIST" : "NONENTITY");
    }

    /**
     * Created By zby on 14:23 2019/6/8
     * 根据用户名和密码查询用户
     *
     * @param phoneOrAccName 目前是手机号码、账户名称
     * @param password       密码
     * @param request        请求
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public Result login(String phoneOrAccName, String password, HttpServletRequest request, HttpServletResponse response) {
        ifTrueThrow(isAnyBlank(phoneOrAccName, password), NOT_EMPTY_USERNAME_PHONE);
        User user = userService.getByAccNameOrPhone(phoneOrAccName, password).getResultData();
        ifNullThrow(user, ERR_USERNAME_OR_PHONE);
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_USER, user);
        session.setAttribute(TOKEN, user.getToken());
        JSONObject jsonObject = getJsonObject(user);
        session.setAttribute(SESSION_NAME, jsonObject.get(SESSION_NAME));
        session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL_TWO_HOUR);
        response.setHeader(SESSION_NAME, jsonObject.getString(SESSION_NAME));
        response.setHeader(TOKEN, user.getToken());
        response.setHeader(USER_ID, isNotNull(user) ? user.getId().toString() : null);
        return ResultUtil.buildSuccess(jsonObject);
    }


    /**
     * Created By zby on 16:48 2019/6/10
     * 登出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Result logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_NAME, null);
        session.setAttribute(USER_ID, null);
        session.setAttribute(TOKEN, null);
        return ResultUtil.buildSuccess(true);
    }

    private JSONObject getJsonObject(User user) {
        JSONObject body = new JSONObject();
        body.put("id", user.getId());
        SignInTypeEnum signInType = user.getSignInType();
        body.put(SESSION_NAME, isNull(signInType) ? null :
                (signInType.equals(SIGN_IN_TYPE_ENTERPRISE) ? user.getCompanyName() : user.getPhone())
        );
        return body;
    }
}
